const Controller = require("egg").Controller
// eslint-disable-next-line no-unused-vars
let {getToDay, sendStat, group} = require("../../extend/helper")
let gameConfig = require("../../../config/game")
/** @param {import("egg").Application} app */
module.exports = function (app) {
	const UserEmpireStore = app.model.Game.UserEmpireStore
	const GameUserSign = app.model.Game.GameUserSign
	const constant = app.config.constant
	class GameData extends Controller {
		constructor(ctx) {
			super(ctx)
			this.Game = this.ctx.model.Game
			this.constant = this.app.config.constant
			this.serverConfig = this.config.serverConfig
			this.ShareInfo = this.app.model.ShareInfo
		}

		async init() {
			let ads = await this.app.cache.ads
			let adList = ads.filter((val) => {
				return val.stat == 1 && val.aid == this.ctx.userInfo.aid
			}).map((v) => {
				let {image_url, share_img, ...val} = v
				delete val.stat
				val.image_url = image_url ? this.serverConfig.imgServer + image_url : null
				val.share_img = share_img ? this.serverConfig.imgServer + share_img : null
				return val
			})// 广告

			let share_info = await this.ShareInfo.findAll({
				where: {
					aid: this.ctx.userInfo.aid,
					stat: true
				},
				attributes: ["key", "image_url", "title", "attr"]
			})
			share_info.forEach((v) => {
				v.image_url = this.config.serverConfig.imgServer + v.image_url
			})
			// 分享
			let ServenDayReWard = []
			let isSign = false
			let res = {}
			try {
				res = await this.service.empire.getSignReward(this.ctx.userInfo.oid)
				ServenDayReWard = res.signReward
				isSign = Boolean(res.hasSign)
			} catch (error) {
				this.ctx.logger.error(error)
			}
			// this.ctx.body = sendStat(this.constant.NORMAL, myAds)
			this.ctx.body = sendStat(this.constant.NORMAL,
				{
					inviteWelfare: this.service.empire.getAllReward(),
					popularity_percent: gameConfig.popularity_percent,
					level_to_duration: gameConfig.level_to_duration,
					adList,
					share_info,
					ad: gameConfig.ad,// 等级=> 时间减半区间
					ServenDayReWard,//: gameConfig.ServenDayReWard,
					unlock_price: gameConfig.unlock_price,
					signTime: Number(res.signTime),
					isSign: Number(isSign)
				})
		}

		async updateStoreData() {
			let ctx = this.ctx
			let body = ctx.request.body
			let stores = await this.app.cache.empireStore
			let ids = stores.map(obj => "" + obj.id)
			ctx.validate({
				store_id: ids,
				state: ["open", "close", undefined],// 不传拉到
				level: "pintstr",
			}, ctx.request.body)
			let [data, create] = await this.Game.UserEmpireStore.findOrCreate({
				defaults: {
					level: body.level,
					storeid: body.store_id,
					oid: ctx.userInfo.oid,
					sales_round: ctx.gameUser.sell_count
				},
				where: {
					sales_round: ctx.gameUser.sell_count,
					storeid: body.store_id,
					oid: ctx.userInfo.oid
				}
			})
			let msg = "创建成功"
			let stat = true
			ctx.logger.info({oid: ctx.userInfo.oid, level: body.level, storeid: body.store_id})
			if (!create) {
				if (data.level != body.level) {
					if (body.level < data.level) {
						this.app.logger.error({oid: ctx.userInfo.oid, level: body.level, storeid: body.store_id})
					}
					data.level = body.level
					msg = "升级成功"
					await data.save()
				} else {
					msg = "商店数据无变化"
					stat = false
				}
			}
			ctx.body = sendStat(this.constant.NORMAL, {
				stat, msg
			})
			// 更新商店数据
		}

		async getStoreData() {
			let store = await this.app.cache.empireStore
			let userStore = await UserEmpireStore.findAll({
				where: {
					oid: this.ctx.gameUser.oid,
					sales_round: this.ctx.gameUser.sell_count
				}
			})
			this.ctx.logger.warn(this.ctx.gameUser.oid + "获取商店列表")
			let userStoreMap = {}
			userStore.forEach((obj) => {
				userStoreMap[obj.storeid] = obj
			})
			let StroreList = Array.from(new Array(3), () => [])
			store.map((v, index) => {
				v = JSON.parse(JSON.stringify(v))
				if (userStoreMap[v.id]) {
					let {total_current_income, level} = userStoreMap[v.id]
					Object.assign(v, {total_current_income, level, state: "open"})
				} else {
					v.level = 1
					v.state = "close"
					v.total_current_income = 0
				}
				let {id: store_id, ...obj} = v
				obj.store_id = store_id
				StroreList[index / 9 | 0].push(obj)
				return obj
			})
			this.ctx.body = sendStat(this.constant.NORMAL, StroreList)
		}

		async sellStore() {
			let body = this.ctx.request.body
			this.ctx.validate({map_id: "pintstr"}, body)
			//map_id表示为 12 地图
			let gameUser = this.ctx.gameUser
			//限制
			/* 			let lastSellInfo = await this.Game.StoreSell.max(
				"sell_time", {
					where: {
						oid: gameUser.oid,
					}
				}
			)
			if (lastSellInfo && lastSellInfo instanceof Date && Date.now() - lastSellInfo < 1000 * 3600 * 24) {
				this.ctx.body = sendStat(this.constant.NORMAL, {
					stat: false,
					msg: "出售频率每天一次",
					sales_round: gameUser.sell_count
				})
				return
			} */
			//限制
			// console.log(lastSellInfo)
			let res = await this.Game.UserEmpireStore.count(
				{
					where: {
						oid: gameUser.oid,
						sales_round: gameUser.sell_count,
						storeid: {
							$gt: (body.map_id - 1) * 9,
							$lte: body.map_id * 9
						}
					}
				}
			)// 商店统计 //当前地图
			//1-9
			let Op = this.app.Sequelize.Op
			let sellStat = false
			if (((body.map_id == 1) && res >= 6) || ((body.map_id != 1) && res >= 1)) {
				gameUser.total_coin = 0
				// 保留未出售的数据
				this.Game.UserEmpireStore.update({
					sales_round: gameUser.sell_count + 1
				}, {
					where: {
						oid: gameUser.oid,
						sales_round: gameUser.sell_count,
						[Op.or]: [
							{
								storeid: {
									[Op.lte]: (body.map_id - 1) * 9,
								}
							},
							{
								storeid: {
									[Op.gt]: body.map_id * 9,
								}
							}]
					}
				})
				// 保留道具
				let additionProp = await this.app.cache.additionProp
				let currentMapIds = additionProp.filter((v) => {
					return v.map_id == body.map_id
				}).map(o => o.id)
				await this.Game.UserProp.update({
					level: gameUser.level + 1
				}, {
					where: {
						oid: gameUser.oid,
						level: gameUser.level,
						propid: {
							[Op.notIn]: currentMapIds
						}
					}
				})
				this.Game.StoreSell.create({oid: gameUser.oid})
				gameUser.sell_count++
				gameUser.level++
				await gameUser.save()
				sellStat = true
			}
			this.ctx.body = sendStat(this.constant.NORMAL, {
				stat: sellStat,
				msg: "",
				sales_round: gameUser.sell_count,
				storeNum: res
			})
		}

		async lastSellTime() {
			this.ctx.body = sendStat
			let gameUser = this.ctx.gameUser
			let lastSellInfo = await this.Game.StoreSell.max(
				"sell_time", {
					where: {
						oid: gameUser.oid,
					}
				}
			)
			if (!lastSellInfo) {
				this.ctx.body = sendStat(constant.EMPIRE_NO_SELL_BEFORE, null)
				return
			}
			this.ctx.body = sendStat(constant.NORMAL, lastSellInfo && Date.parse(lastSellInfo))
		}

		async getUserProp() {// 获取用户当前阶段的加成道具
			let ctx = this.ctx
			let Game = this.Game
			let data = await this.app.cache.additionProp

			let isSycee = data.filter(function (params) {
				return params.cost_type == 3
			}).map(params => params.id)
			let userProp = await Game.UserProp.findAll(
				{
					where: {
						oid: this.ctx.gameUser.oid,
						$or: [{propid: {$in: isSycee}},
							{level: ctx.gameUser.level}]
					}
				}
			)
			// level 处理
			// 元宝道具不限制等级
			let propByMap = Array.from(new Array(3), () => [])
			data.map((v) => {// 全部道具
				let {detail, id: prop_id, cost_type, tool_type, price: cost, prop_name, map_id} = v
				let val = {detail, prop_id, cost_type, tool_type, cost, prop_name, map_id}
				let propObj = userProp.find((prop) => {
					return prop.propid == val.prop_id
				})
				if (!propObj) {
					val.stat = false
					val.times = 0
				} else {
					val.stat = propObj.stat
					val.times = propObj.num
				}
				propByMap[Number(map_id - 1)].push(val)
				return val
			})
			ctx.body = sendStat(this.constant.NORMAL, propByMap)
		}


		async addUserProp() {
			let Game = this.Game
			let body = this.ctx.request.body
			this.ctx.validate({prop_id: "numstr"}, body)

			let data = await this.app.cache.additionProp

			let id = data.find((v) => {
				return v.id == body.prop_id
			})

			if (!id) {
				this.ctx.body = sendStat(this.app.config.constant.ERROR_PARAM_UPLOAD_MISS, [{
					field: "prop_id",
					code: "data compete miss"
				}])
				return
			}
			let isSycee = data.filter(function (params) {
				return params.cost_type == 3
			}).map(params => params.id)
			let addPropId = Number(body.prop_id)

			let level = isSycee.includes(addPropId) ? {} : {level: this.ctx.gameUser.level}
			let f = await Game.UserProp.findOrCreate({
				where: {
					oid: this.ctx.gameUser.oid,
					propid: addPropId,
					...level
				},
				defaults: {
					level: !isSycee.includes(addPropId) ? this.ctx.gameUser.level : 0,
					propid: addPropId,
					oid: this.ctx.gameUser.oid
				}
			})// 确认存在记录
			f[0].num++
			await f[0].save()
			this.ctx.body = sendStat(this.constant.NORMAL, {
				stat: true
			})
		}

		async getAllProp() {
			let ctx = this.ctx
			let data = await this.app.cache.additionProp
			ctx.body = sendStat(this.constant.NORMAL, data)
		}

		async sign() {
			let ctx = this.ctx
			let oid = ctx.gameUser.oid
			let o = await ctx.service.empire.getSignReward(oid)
			if (o.hasSign) {
				ctx.body = sendStat(constant.EMPIRE_SIGN_FAIL, {msg: "重复签到"})
				return
			} else {
				await GameUserSign.upsert({
					id: o.signList[o.signTime % 7] && o.signList[o.signTime % 7].id,
					sign_time: Date.now(),
					oid,
					stat: o.signTime == 0 ? 2 : 1,// 默认的
					reward: o.signReward[o.signTime % 7] || {} // 索引 减少1
				})
				await this.app.redis.del("empire#getHistorySignCache#" + oid)
				ctx.body = sendStat(constant.NORMAL)
				return
			}
		}


		async taskList() {
			let ctx = this.ctx
			let oid = this.ctx.userInfo.oid
			let usertskList = []
			let userTsk = (await this.Game.GameUserTsk.findAll({
				where: {
					oid
				},
				attributes: ["state", "tskId"]
			}))
			userTsk.forEach(v => {
				usertskList[v.dataValues.tskId] = v.dataValues
				return v.dataValues
			})
			let sysTskList = await this.app.cache.tskList
			let res = new Array(sysTskList.length)
			for (let i = 0; i < sysTskList.length; i++) {// i+1 为任务 id
				let curUserTask = usertskList[i + 1] || {state: false}
				curUserTask.state = Number(curUserTask.state) || 0
				res[i] = Object.assign(curUserTask, sysTskList[i])
			}
			// let front = res.splice(0, 20)
			// group(res, 20)
			ctx.body = sendStat(constant.NORMAL, group(res, 20))
			//组装数据
		}

		async recTaskReward() {
			this.ctx.validate({
				id: {
					type: "pintstr",
					min: 1,
					max: 40
				}
			}, this.ctx.request.body) // 验证进度
			let tskId = Number(this.ctx.request.body.id)
			let oid = this.ctx.userInfo.oid
			// 获取奖励
			let userTsk = await this.Game.GameUserTsk.findOne({
				where: {
					tskId,
					oid
				}
			})
			if (userTsk && userTsk.state == 1) {
				this.ctx.body = sendStat(constant.EMPIRE_TSK_REC_REPEAT)
				return
			} else if (userTsk) {
				userTsk.state = 1
				userTsk.save()
				this.ctx.body = sendStat(constant.NORMAL)
			} else {
				await this.Game.GameUserTsk.create({
					oid, tskId, state: 1
				})
			}
			this.ctx.body = sendStat(constant.NORMAL)
		}
		async friendHelpCount() {
			let oid = this.ctx.userInfo.oid
			let ucount = await this.ctx.service.empire.getCount(oid)
			this.ctx.body = sendStat(constant.NORMAL, {count: ucount.assistCount})
		}
	}
	return GameData
}